package cn.bm.web.services;

import cn.bm.web.db.DBConfig;
import org.apache.commons.codec.digest.DigestUtils;

import java.sql.*;

/**
 * 操作数据库
 */
public class UserServices {
    public static Boolean login(String username, String password) {//传过来看是否有username 和 password
        Connection conn = DBConfig.getConnection();//建立连接
        try {
            String sql = "SELECT * FROM user WHERE username = ? AND password = ?";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username); // 设置第一个参数为用户名
            pstmt.setString(2, DigestUtils.md5Hex(password)); // 使用安全库计算MD5值，并设置第二个参数为密码的MD5值

            ResultSet resultSet = pstmt.executeQuery(); // 使用executeUpdate()方法执行插入操作

            if (resultSet.next()) {
                System.out.println("查询成功");
                return true;
            } else {
                System.out.println("查询失败");
                return false;
            }
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        } finally {
            try {
                conn.close();
            } catch (SQLException e) {
                System.out.println(e.getMessage());
            }
        }
        return false;
    }

    public static Boolean register(String username, String password, String recheckpassword) {
        if(password.equals(recheckpassword)==false) {
            return false;
        }
        Connection conn = DBConfig.getConnection();
        try{
            String sql = "insert into user values(?, ?)";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username); // 设置第一个参数为用户名
            pstmt.setString(2, DigestUtils.md5Hex(password)); // 使用安全库计算MD5值，并设置第二个参数为密码的MD5值

            int rowsAffected = pstmt.executeUpdate(); // 使用executeUpdate()方法执行插入操作

            if (rowsAffected > 0) {
                System.out.println("插入成功");
                return true;
            } else {
                System.out.println("插入失败");
                return false;
            }
        }catch (SQLException ex){
            System.out.println(ex.getMessage());
        }finally {
            try {
                conn.close();
            } catch (SQLException e) {
                System.out.println(e.getMessage());
            }
        }
        return false;
    }
}
